const { pool, add, edit } = require('./baseModel.js')

exports.checkNickName = async (nick) => {
    let result = await pool.query('select * from user_info where nickName=?', [nick])
    return result[0]
}

exports.checkUserPhone = async (phone) => {
    let result = await pool.query('select * from user_info where user_phone=?', [phone])
    return result[0]
}

exports.register = async (fields) => {
    // 此处并不需要try/catch，错误会被调用者捕获
    return await add('user_info', fields)
}

exports.login = async (fields) => {
    let result = await pool.query('select * from user_info where user_phone=? and password=?', [fields.user_phone, fields.password])
    return result[0]
}

exports.uploadUserPhoto = async (files) => {
    // console.log(files.user_photo.name);
    const fs = require('fs')
    let name = Date.now() + '_' + files.user_photo.name
    fs.writeFileSync(uploads + name, fs.readFileSync(files.user_photo.path))
    return '/uploads/' + name;
}

exports.editUser = async (fields) => {
    let where = { id: fields.id }
    delete fields.id
    return await edit('user_info', fields, where)
}

exports.findById = async (id) => {
    let result = await pool.query('select * from user_info where id=? and isDel=0', [id])
    return result[0]
}

exports.deleteById = async (id) => {
    return edit('user_info', { isDel: 1 }, { id })
}

exports.getListByPage = async (query) => {
    // console.log(query);
    let sql = 'select * from user_info where 1 '
    let data = []
    if (query.nickName) {
        sql += `and nickName like ? `
        data.push('%' + query.nickName + '%')
    }
    if (query.user_sex) {
        sql += `and user_sex=? `
        data.push(query.user_sex)
    }
    if (query.user_phone) {
        sql += `and user_phone like ? `
        data.push('%' + query.user_phone + '%')

    }
    sql += `and isDel=0 order by id limit ?,10`
    data.push((query.pageIndex - 1) * 10)
    console.log(sql);
    console.log(data);
    let result = await pool.query(sql, data)
    // console.log(result[0]);
    return result[0]
}